package com.motu.monstercity.server.game.timedtask;

import com.motu.monstercity.server.game.commondata.feast.FeastMain;
import com.motu.monstercity.server.game.logic.FeastManager;
import com.motu.monstercity.server.game.userdata.FeastChatRecord;
import com.motu.monstercity.server.game.userdata.ServerFeast;
import com.motu.monstercity.server.game.userdata.UserFeastRecord;
import com.motu.vertx.module.utility.model.EntityManager;
import com.motu.vertx.module.utility.threadpool.DBLogManager;
import com.motu.vertx.module.utility.toolset.TimeUtils;
import com.motu.vertx.module.utility.toolset.Tool;
import io.vertx.core.json.JsonObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

public class ServerfeastTask implements Runnable, Delayed {
	public final static Logger logger = LoggerFactory.getLogger(ServerfeastTask.class);

	private int serverId;// 服务器id
	private String uniqKey;// 举办者的userid 和feastmainid组成的唯一值
	private long execTime;// 结束时间,任务的执行时间 举办时间+时长
	private JsonObject jsonObject;

	private int getServerId() {
		return this.serverId;
	}
	private String getUniqKey() {
		return this.uniqKey;
	}
	private long getExecTime() {
		return this.execTime;
	}
	private JsonObject getJsonObject() {
		return this.jsonObject;
	}


	public ServerfeastTask(JsonObject obj) {
		this.serverId = obj.getInteger("server_id");
		this.uniqKey = obj.getString("uniq_key");
		this.execTime = obj.getLong("end_time");
		this.jsonObject = obj;
	}

	@Override
	public void run() {
		TimedTaskManager.sendWorkTaskRetry(TimeTaskCmd.WORK_SERVER_FEAST, getJsonObject());// 发送失败进行重发
	}

	@Override
	public long getDelay(TimeUnit unit) {
		return unit.convert(getExecTime() - TimeUtils.getCurTime(), TimeUnit.SECONDS);
	}

	@Override
	public int compareTo(Delayed o) {
		ServerfeastTask that = (ServerfeastTask) o;
		return getExecTime() > that.execTime ? 1 : (getExecTime() < that.execTime ? -1 : 0);
	}

	/**
	 *  处理派对结束的逻辑
	 * @param task
	 */
	public static void runTask(JsonObject task){
		try {
			logger.info("### ServerfeastTask runTask = " + task);
			String uniqKey = task.getString("uniq_key");// 派对举办者的userid和feastmainid 组成的唯一值
			int serverId = task.getInteger("server_id");// 服务器id,
			long endTime = task.getLong("end_time");
			ServerFeast serverFeast = FeastManager.getServerFeastByUniqKey(serverId, uniqKey);// 派对对象
			if (serverFeast != null) {// 给举办者发邮件奖励, 生成举办记录
				FeastMain feastMain = FeastManager.getFeastMain(serverFeast.getFeastMainId());
				if (feastMain == null) {
					return;
				}
				long createTime = 0L;
				if (feastMain.isCommonFeast()) {//普通派对会提前结束，避免重复执行
					createTime = endTime - feastMain.getDurationTime();// 获取举办时间
				}
				FeastManager.handleFeastComplete(serverFeast, createTime);
			}
		} catch (Exception e){
			String errMsg = Tool.getException(e);
			logger.error("###ServerfeastTask error:" + errMsg);
			DBLogManager.addServerCrashLog(999999, errMsg);
		}
	}
}
